<template>
  <div>
    <el-dialog :title="`PH_IPT_${formData.seqNo}`" :visible.sync="isShowIPT" :close-on-click-modal="false"
      :before-close="handleCloseStorage" :width="screenWidth > 1310 ? '55%' : '70%'" v-dialogDrag>
      <el-form :model="formData" label-width="70px" ref="ruleForm" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="24" class="gz-form-row">
          <el-col :xs="6" :sm="6" :md="6" :lg="5" :xl="4">
            <el-form-item :label="$t('common.step_number')" class="seqNo">
              <el-input v-model="formData.seqNo" disabled placeholder="" style="width: 70px" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="6" :sm="6" :md="6" :lg="4" :xl="3">
            <el-form-item :label="$t('common.order')" label-width="40px">
              <el-input type="number" v-model="formData.stepSort" style="width: 55px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.isActive">{{$t('common.enable')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.isAuto">{{$t('common.auto_start')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
                    <el-form-item label="数字签名">
                        <el-checkbox v-model="formData.signitature"></el-checkbox>
                    </el-form-item>
                </el-col> -->
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.mode">{{$t('common.operation_signature')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :md="5" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.checks">{{$t('common.review_confirmation')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="7" :md="8" :lg="6" :xl="6">
            <el-form-item :label="$t('basic.stage_name')" prop="phaseDesc">
              <el-input disabled v-model="formData.phaseDesc" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item :label="$t('recipe.start_delay')" class="append" prop="startDelay">
              <el-input v-model="formData.startDelay" placeholder="" type="number">
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
          </el-col>
          <!-- </el-row>
        <el-row :gutter="24"> -->

          <el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item label-width="0" style="text-align: right;" class="btnGourd">
              <el-button type="primary" size="mini" :disabled="isreadOnly" @click="handleAdd()">{{ $t("common.add") }}</el-button>
              <el-button type="primary" size="mini" :disabled="isreadOnly" @click="handleEdit()">{{ $t("common.edit") }}</el-button>
              <el-button type="primary" size="mini" :disabled="isreadOnly" @click="handleDel()">{{ $t("common.remove") }}</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <div>

          <el-row :gutter="24" style="clear:both">
            <el-col :xs="24">
              <div class="tableAuto" style="padding:0 12px">
                <el-table :data="tableData" height="180px" @row-click="rowClick" style="width:100%" border stripe v-loading="tableLoading"
                  :header-cell-style="{background:'#EAEBEC'}" ref="refTable" highlight-current-row>
                  <el-table-column label="" width="50" align="center">
                    <template slot-scope="scope">
                      <div>
                        <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column type="index" :label="$t('common.number')" width="80" align="center"></el-table-column>
                  <el-table-column prop="paraName" show-overflow-tooltip :label="$t('recipe.data_name')"></el-table-column>
                  <el-table-column prop="group" show-overflow-tooltip :label="$t('run.data_group')">
                    <template slot-scope="scope">
                      {{parseFloat(scope.row.groups) === 0 ? '质量数据' : scope.row.groups == 1 ? '过程数据' : ''}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="type" show-overflow-tooltip :label="$t('run.data_type')">
                    <template slot-scope="scope">
                      {{getDataType(scope.row.type)}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="uom" show-overflow-tooltip :label="$t('basic.company')"></el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :xs="24">
              <div class="pagination-area">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]"
                  :page-size="pager.pageSize" :current-page="pager.pageNum" layout="total, sizes, prev, pager, next, jumper"
                  :total="pager.total">
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-row :gutter="24">
          <el-col :xs="23" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label-width="0">
              <!-- <el-checkbox v-model="formData.confirm"> -->
              <p style="font-weight: bold">{{$t('recipe.phase_info')}}</p>
              <!-- </el-checkbox> -->
            </el-form-item>
          </el-col>
          <el-col :xs="23" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('common.operating_instructions')">
              <el-input rows="2" type="textarea" v-model="formData.guideInfo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="23" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('basic.remarks')">
              <el-input type="textarea" rows="2" v-model="formData.flastModifyComment" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <!-- </el-row> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :disabled="isreadOnly" :loading="loading" @click="handleConfirmStorage('ruleForm')">保
          存</el-button>
        <el-button @click="handleCloseStorage()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>

    </el-dialog>

    <el-dialog :title="title" :visible.sync="isShowAdd" :close-on-click-modal="false" :before-close="handleCloseAdd"
      :width="screenWidth > 1024 ? '30%' : '55%'" v-dialogDrag>
      <el-form :model="ruleForm" label-width="85px" ref="formName" size="small" :rules="addRules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item :label="$t('recipe.data_name')" prop="paraName">
              <el-input type="text" v-model="ruleForm.paraName" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('run.data_type')" prop="type" class="selectClass">
              <el-select v-model="ruleForm.type" placeholder="" clearable @change="handleDataType">
                <el-option v-for="(item,index) in dataTypeList" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="ruleForm.type != 2 && ruleForm.type != 3">
            <el-form-item :label="$t('basic.company')" prop="uom" class="selectClass">
              <el-select v-model="ruleForm.uom" placeholder="" clearable>
                <el-option v-for="(item,index) in uomIdList" :key="index" :label="item.fid" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('run.data_group')" prop="groups" class="selectClass">
              <el-select v-model="ruleForm.groups" placeholder="" clearable>
                <el-option v-for="(item,index) in groupList" :key="index+'i'" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="通讯标签" prop="attributId">
              <el-checkbox v-model="ruleForm.useAttribute" @change="changeIo">&nbsp;&nbsp;&nbsp;&nbsp;
                <el-select v-model="ruleForm.attributId" :disabled="!ruleForm.useAttribute" placeholder="" clearable>
                  <el-option v-for="(item,index) in ioAttributeList" :key="index+'i'" :label="item.name" :value="item.fid"></el-option>
                </el-select>
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="ruleForm.type != 2 && ruleForm.type != 3">
            <el-form-item label="录入上限" prop="hi">
              <el-checkbox v-model="ruleForm.hiBool" @change="changeStatu">Hi
                <el-input type="number" :disabled="!ruleForm.hiBool" size="small" v-model="ruleForm.hi" placeholder=""
                  v-enterNumber2></el-input>
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="24" v-if="ruleForm.type != 2 && ruleForm.type != 3">
            <el-form-item label="录入下限" prop="lo">
              <el-checkbox v-model="ruleForm.loBool" @change="changeStatu1">Lo
                <el-input type="number" :disabled="!ruleForm.loBool" size="small" v-model="ruleForm.lo" placeholder=""
                  v-enterNumber2></el-input>
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :disabled="isreadOnly" :loading="loadingTab" @click="handleConfirm('formName')">保
          存</el-button>
        <el-button @click="handleCloseAdd()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { formula } from "@/api/formula"
import { configure } from "@/api/configure"
export default {
  props: {
    isShowIPT: Boolean,
    tdIndex: Number,
    stepObj: Object,
    isreadOnly: Boolean
  },
  data () {
    let hiFn = (rule, value, callback) => {
      if (this.ruleForm.hiBool && !value) {
        callback(new Error('请输入录入上限'));
      } else {
        callback();
      }
    }
    let loFn = (rule, value, callback) => {
      if (this.ruleForm.loBool && !value) {
        callback(new Error('请输入录入下限'));
      } else if (parseFloat(this.ruleForm.hi) < parseFloat(value)) {
        callback(new Error('录入下限不能大于上限'));
      } else {
        callback();
      }
    }
    let uomFn = (rule, value, callback) => {
      console.log(this.ruleForm.type)
      if (this.ruleForm.type === '0' || this.ruleForm.type === '1') {
        if (!value) {
          callback(new Error('单位不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    let attributeIdFn = (rule, value, callback) => {
      if (this.ruleForm.useAttribute) {
        if (!value) {
          callback(new Error('通讯标签不能为空'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      screenWidth: document.body.clientWidth,
      formData: {
        isAuto: true,
        phaseDesc: "数据录入",
        stepDesc: "",
        isActive: false,
        confirm: "",
        guideInfo: "",
        flastModifyComment: "",
        startDelay: "0",
        mode: false,
        checks: false,
        stepSort: 0,
      },
      tableData: [],
      radioId: "",
      rules: {
        startDelay: [{ required: true, message: '请输入启动延时', trigger: 'blur' }],
      },
      title: "添加",
      isShowAdd: false,
      ruleForm: {
        paraName: "",
        type: "",
        uom: "",
        hiBool: false,
        loBool: false,
        groups: "",
        useAttribute: false,
        attributId: ""

      },
      dataTypeList: [{
        label: "Float",
        value: "0"
      }, {
        label: "Int",
        value: "1"
      }, {
        label: "String",
        value: "2"
      }, {
        label: "Bool",
        value: "3"
      }],
      groupList: [{
        label: "质量数据",
        value: "0"
      }, {
        label: "过程数据",
        value: "1"
      }],
      addRules: {
        paraName: [{ required: true, message: '数据名称不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '数据类型不能为空', trigger: 'change' }],
        // uom: [{ validator: uomFn, trigger: 'change' }],
        groups: [{ required: true, message: '数据组不能为空', trigger: 'change' }],
        hi: [{ validator: hiFn, trigger: 'blur' }],
        lo: [{ validator: loFn, trigger: 'blur' }],
        attributId: [{ validator: attributeIdFn, trigger: 'blur' }]
      },
      loading: false,
      stepLoading: false,
      uomIdList: [],
      ioAttributeList: [],
      pager: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableLoading: false,
      loadingTab: false,
      allTable: "",
      hiBool: false,
      loBool: false
    }
  },
  watch: {
    screenWidth (val) {
      this.screenWidth = Number(val)
    },
    isShowIPT (val) {
      if (val) {
        this.radioId = ''
        this.formData.stepDesc = this.stepObj.stepDesc
        this.formData.isActive = this.stepObj.isActive == 1 ? true : false
        this.formData.seqNo = this.tdIndex
        this.formData.phaseDesc = this.stepObj.texts

        this.formData.stepNo = this.tdIndex
        this.formData.mode = this.stepObj.mode == 1 ? true : false
        this.formData.checks = this.stepObj.checks == 1 ? true : false

        if (this.stepObj.fid) {
          this.phaseIptList()
          this.getIoAttributeList()
        } else {
          this.tableData = []
          this.pager.total = 0
          this.ioAttributeList = []
        }
        this.formData.isAuto = this.stepObj.isAuto == 1 ? true : false
        this.formData.fid = this.stepObj.fid
        this.formData.confirm = this.stepObj.confirm == 1 ? true : false
        this.formData.flastModifyComment = this.stepObj.flastModifyComment
        this.formData.guideInfo = this.stepObj.guideInfo
        this.formData.stepSort = this.stepObj.stepSort ?? 0
        this.formData.startDelay = this.stepObj.delayTime

      } else {
        for (let key in this.formData) {
          this.formData[key] = ""
        }
        this.formData.startDelay = 0
        this.title = "添加"
      }
    }
  },
  mounted () {
    const that = this
    window.addEventListener('resize', function () {
      that.screenWidth = document.body.offsetWidth;
    })
  },
  created () {
    this.getUomList()
  },
  methods: {
    // 获取计量单位列表
    getUomList () {
      const param = {
        page: 1,
        size: 9999
      }
      configure.getUomList(param).then(res => {
        if (res.code == 200) {
          this.uomIdList = res.data.rows
        }
      }).catch(e => {

      })
    },
    getIoAttributeList () {
      const param = {}
      formula.getIoAttributeList(param).then(res => {
        if (res.code == 200) {
          this.ioAttributeList = res.data.rows
        }
      })
    },
    phaseIptList () {
      const param = {
        phaseId: this.stepObj.fid,
        page: this.pager.pageNum,
        size: this.pager.pageSize
      }
      this.tableLoading = true
      formula.phaseIptList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.allTable = res.data.rows
          this.tableData = res.data.rows.filter(item => {
            return item.paraName && this.$util.isNumber(item.type) && item.groups != 3
          })
          let item = res.data.rows.find(item => {
            return (item.target !== '' && item.target !== null) || item.groups == 3
          }) || {}

          // if (!parseFloat(this.formData.startDelay)) {
          //   this.formData.startDelay = item.target
          // } else {
          //   this.formData.startDelay = 0
          // }
          console.log(item)
          this.fid = item.fid
          if (JSON.stringify(item) != '{}') {
            this.pager.total = res.data.total - 1
          } else {
            this.pager.total = res.data.total
          }

        }
      })
    },
    rowClick (row) {
      this.radioId = row.fid;
      this.$refs.refTable.setCurrentRow(row);
    },
    handleCloseStorage () {
      this.$emit("closePH", "IPT")
    },
    handleDataType (val) {
      if (val == 2 || val == 3) {
        this.$set(this.ruleForm, 'uom', '')
        this.$set(this.ruleForm, 'hi', '')
        this.$set(this.ruleForm, 'lo', '')
        let fields = this.$refs['formName'].fields;
        for (let i = 0; i < fields.length; i++) {
          if (fields[i].prop == 'uom' || fields[i].prop == 'hi' || fields[i].prop == 'lo') {
            fields[i].resetFields()
          }
        }
      } else {
        this.addRules.groups[0].required = true
      }
    },
    handleAdd () {
      this.title = "添加"
      this.ruleForm = {}
      try {
        this.$refs['formName'].resetFields();
      } catch (e) { }
      this.ruleForm.loBool = false
      this.ruleForm.hiBool = false
      this.ruleForm.useAttribute = false
      this.isShowAdd = true
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error('请选择修改数据');
        return
      }
      this.title = "编辑"
      formula.phaseIptFind(this.radioId).then(res => {
        if (res.code == 200) {
          this.ruleForm = Object.assign({}, res.data)
          this.ruleForm.type = res.data.type + ""
          this.ruleForm.hiBool = res.data.hi ? true : false
          this.ruleForm.loBool = res.data.lo ? true : false
          this.ruleForm.useAttribute = res.data.useAttribute ? true : false
          this.isShowAdd = true
        }
      })
    },
    handleCloseAdd () {
      this.isShowAdd = false
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {}
          if (this.ruleForm.paraName == '启动延时') {
            this.$message.error('名称已存在');
            return
          }
          if (this.title == '添加') {
            param = {
              paraName: this.ruleForm.paraName,
              uom: this.ruleForm.uom,
              groups: this.ruleForm.groups,
              hi: this.ruleForm.hiBool ? this.ruleForm.hi : '',
              lo: this.ruleForm.loBool ? this.ruleForm.lo : '',
              type: this.ruleForm.type,
              phaseId: this.stepObj.fid,
              operationId: this.stepObj.stepId,
              attributId: this.ruleForm.attributId,
              useAttribute: this.ruleForm.useAttribute == true ? 1 : 0,
              stepSort: this.formData.stepSort,
              delayTime: this.formData.startDelay,
            }
          } else {
            param = Object.assign({}, this.ruleForm)
            param.useAttribute = this.ruleForm.useAttribute ? 1 : 0
          }
          this.loadingTab = true
          formula.phaseIptAdd(param, this.title).then(res => {
            this.loadingTab = false
            if (res.code == 200) {
              this.isShowAdd = false
              this.phaseIptList()
            } else {
              this.$message.error(res.msg);
            }
          })
        } else {
          return false
        }
      })
    },
    async handleDel () {
      if (this.radioId === '') {
        this.$message.error('请选择要删除的数据');
        return
      }
      formula.phaseIptFind(this.radioId).then(res => {
        if (res.code == 200) {
          let fid = res.data.fid
          let that = this
          this.$customConfirm({
            onok () {
              formula.phaseIptRemove(fid).then(res => {
                if (res.code == 200) {
                  that.phaseIptList()
                  that.radioId = ''
                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                }
              })
            }
          });
        }
      })
    },
    handleConfirmStorage (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.tableData.length == 0 && this.formData.isAuto) {
            this.$message.error('请添加数据信息');
            return
          }
          const param = {
            phaseDesc: this.formData.phaseDesc,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            checks: this.formData.checks == false ? 0 : 1,
            operationId: this.stepObj.operationId,
            type: this.stepObj.type,
            mode: this.formData.mode == false ? 0 : 1,
            seqNo: this.stepObj.seqNo,
            phaseCode: this.stepObj.phaseCode,
            confirm: this.formData.confirm == false ? 0 : 1,
            flastModifyComment: this.formData.flastModifyComment,
            guideInfo: this.formData.guideInfo,
            delayTime: this.formData.startDelay,
            stepNo: this.stepObj.stepNo,
            serialNo: this.stepObj.serialNo,
          }
          if (this.formData.fid) {
            param.fid = this.formData.fid
          }
          formula.phaseAdd(param).then(res => {
            if (res.code == 200) {
              this.phaseIptAdd()

            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })

    },
    phaseIptAdd () {
      const item = this.allTable.find(item => {
        return item.target !== '' && item.target !== null
      }) || {}
      const param = {
        paraName: "启动延时",
        uom: "分",
        target: this.formData.startDelay,
        phaseId: this.stepObj.fid,
        fid: item.fid,
        groups: 3,
        type: 1,
      }
      formula.phaseIptAdds(param).then(res => {
        this.loadingTab = false
        if (res.code == 200) {
          let obj = {
            mode: this.stepObj.mode,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            operationId: this.stepObj.operationId,
            seqNo: this.stepObj.seqNo,
            serialNo: this.stepObj.serialNo,
            text: this.stepObj.phaseDesc
          }
          this.$emit("uptionData", obj)
          this.$emit("closePH", "IPT")
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    handleSizeChange (val) {
      this.pager.pageSize = val
      this.phaseIptList()
    },
    handleCurrentChange (val) {
      this.pager.pageNum = val;
      this.phaseIptList()
    },
    getDataType (id) {
      if (!id && id !== 0) return ''
      return this.dataTypeList.find(item => item.value == id).label
    },
    changeStatu () {
      if (!this.ruleForm.hiBool) {
        this.ruleForm.hi = ''
      }
      this.$forceUpdate()
    },
    changeStatu1 () {
      if (!this.ruleForm.loBool) {
        this.ruleForm.lo = ''
      }
      this.$forceUpdate()
    },
    changeIo (val) {
      if (!val) {
        this.ruleForm.attributId = ''
      }
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped>
@media screen and (max-width: 1024px) {
  .tableAuto {
    width: 100%;
    overflow: auto;
  }
}
.rightAdd {
  color: #00a09d;
  cursor: pointer;
  font-size: 20px;
}
.selectClass >>> .el-select {
  width: 100%;
}
@media screen and (max-width: 1200px) {
  .btnGourd {
    text-align: left !important;
  }
}
.pagination-area {
  padding: 10px;
}
.append >>> .el-input-group__append {
  padding: 0 10px;
}
/* .seqNo >>> .el-input__inner{
        padding: 0 0 0 12px;
    } */
.btnGourd >>> .el-button--mini {
  padding: 7px 11px;
}
</style>
